package com.lib76.DBInfo.service;

import java.sql.SQLClientInfoException;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * JPA连接服务
 * @author 张浩
 * @version 0.0.1
 */
public class JPALinkServer {

	/**
	 * 获取数据库连接配置
	 * @param dbType	数据库类型
	 * @param ip	IP地址
	 * @param port	
	 * @param userName
	 * @param userPwd
	 * @param databaseName
	 * @return
	 * @throws SQLClientInfoException 
	 */
	public static Properties getProperties(DatabaseTypeEnum dbType,String ip,Integer port,String userName,String userPwd,String databaseName) throws SQLClientInfoException{
		Properties properties = new Properties();
		if(DatabaseTypeEnum.MYSQL.equals(dbType)){
			properties.put("javax.persistence.jdbc.url", "jdbc:mysql://"+ip+":"+port+"/"+databaseName+"?characterEncoding=utf-8");
		}else{
			throw new SQLClientInfoException();
		}
		properties.put("javax.persistence.jdbc.user", userName);
		properties.put("javax.persistence.jdbc.password", userPwd);
		return properties;
	}
	
	/**
	 * 获取数据库表对象管理
	 * @param dbType
	 * @param properties
	 * @return
	 */
	public static EntityManager getEntityManager(DatabaseTypeEnum dbType,Properties properties){
		EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(dbType.name(),properties);
		return entityManagerFactory.createEntityManager();
	}
}
